package org.javaboy.vhr.controller;

import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class SessionUtils {
    private static MockHttpSession session;

    public static MockHttpSession session(MockMvc mvc) throws Exception {
        if (session == null) {
            session = (MockHttpSession)
                    mvc.perform(post("/doLogin")
                            .contentType(MediaType.APPLICATION_JSON)
                            .content("{\"username\":\"admin\",\"password\":\"123\",\"code\":\"JdIp\"}")
                            .accept(MediaType.APPLICATION_JSON)
                    )
                            .andExpect(status().isOk())
                            .andExpect(jsonPath("$.status").value(200))
                            .andExpect(jsonPath("$.obj").exists())
                            .andDo(print())
                            .andReturn()
                            .getRequest()
                            .getSession();
        }
        return session;
    }
}
